/*
 *  Copyright (c) 2017. 郑州仁中和科技有限公司.保留所有权利.
 *                        http://www.rzhkj.com/
 *        郑州仁中和科技有限公司保留所有代码著作权.如有任何疑问请访问官方网站与我们联系.
 *        代码只针对特定客户使用，不得在未经允许或授权的情况下对外传播扩散.恶意传播者，法律后果自行承担.
 *        本代码仅用于龐帝業務系统.
 *
 */

package com.ponddy.inter.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ponddy.classroom.entity.Classroom;
import com.ponddy.core.entity.Page;
import com.ponddy.core.tools.DateTools;
import com.ponddy.wechat.service.WeiXinTplMsgSV;
import com.ponddy.setting.entity.Setting;
import com.ponddy.setting.service.SettingSV;
import com.ponddy.tutor.entity.Tutor;
import com.ponddy.tutor.service.TutorSV;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 消息提醒接口
 * Created by lixin on 2017/8/19.
 */
@Service
public class NotifyJobSVImpl implements NotifyJobSV {

    @Reference
    WeiXinTplMsgSV weiXinTplMsgSV;

    @Reference
    TutorSV tutorSV;

    @Reference
    SettingSV settingSV;

    /**
     * 上课时间提醒
     * 1.查询所有老师
     * 2.查询老师课程
     * 3.发送即将上课通知
     */
    @Override
    public void reminderClassroom() {
        //1.查询所有老师
        Page<Tutor> tutorPage = new Page<>();
        Tutor tutor = new Tutor();
        tutor.setState(Tutor.State.Activate.name());
        int total = tutorSV.count(tutor);
        if (total <= 0) return;
        tutorPage.setTotalRow(total);

        Integer attendTime = settingSV.load(Setting.Key.Wechat_Attend_Course_Notification_Template_Time, Integer.class);
        if (attendTime == null) return;

        Date curDate = DateTools.toUtc(new Date());
        String minuteDate = DateTools.format(curDate, "yyyy-MM-dd HH:mm");
        curDate = DateTools.stringToDate(minuteDate + ":00");
        long currDate = curDate.getTime();
        long ms = 60000;//分转毫秒 单位

        for (int curPage = 0; curPage < tutorPage.getTotalPage(); curPage++) {
            //2.查询老师课程
            List<Tutor> tutorList = tutorSV.listTutor(tutor, tutorPage.genRowStart(), tutorPage.getPageSize());
            if (tutorList == null || tutorList.isEmpty()) continue;

            tutorList.forEach(tutorObj -> {
                Tutor tutorLoadAll = tutorSV.loadTutorAll(tutorObj.getTutorCode());
                if (tutorLoadAll.getClassroom() != null) {
                    Classroom classroom = tutorLoadAll.getClassroom();
                    Date courseTime = classroom.getCourseTime();
                    courseTime = DateTools.stringToDate(DateTools.format(courseTime, "yyyy-MM-dd HH:mm") + ":00");
                    //公式：[当前时间] + [提前时间] = [课程开课时间]
                    if (currDate + ms * attendTime == courseTime.getTime()) {
                        //3.发送即将上课通知
                        weiXinTplMsgSV.reminderClassroom(classroom);
                    }
                }
            });
        }
    }
}
